package com.link.base.base.mpconfig.service;

import com.link.base.base.mpconfig.model.Mp;
import com.link.base.wechat.wxtoken.util.WxTokenUtil;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.DateUtil;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Service;


import java.util.Date;

/**
 * 小程序token service 实现类
 *
 * @author lujiang
 * date 2019-03-11
 */
@Service
public class MpTokenServiceImpl extends BasicServiceImpl<Mp> implements MpTokenService {
    /**
     * 小程序access_token redisKey前缀
     */
    private static final String WX_MP_TOKEN_REDIS_KEY = "wx_mp_token_";
    /**
     * access_token有效期
     */
    private static final int MP_EXPIRE_TIME = 7200;

    @Override
    public String getMpAccessToken(Mp mp) throws Exception {
        if (mp == null) {
            throw new ServiceException("MPCONFIG-004");
        }
        String mpAppId = mp.getAppId();
        String mpAppSecret = mp.getAppSecret();
        if (StringUtils.isBlank(mpAppId) || StringUtils.isBlank(mpAppSecret)) {
            throw new ServiceException("MPCONFIG-005");
        }
        String accessToken;
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            String redisKey = WX_MP_TOKEN_REDIS_KEY + mpAppId;
            accessToken = j.hget(redisKey, "access_token");
            //  @TODO 暂时修改token的获取逻辑，每次都要调用获取接口
//            if (StringUtils.isBlank(accessToken)) {
            accessToken = WxTokenUtil.getAccessTokenBySecret(mpAppId, mpAppSecret);
            j.hset(redisKey, "access_token", accessToken);
            j.hset(redisKey, "refresh_time", DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
            j.expire(redisKey, MP_EXPIRE_TIME);
//            }
        } finally {
            RedisUtil.returnResource(j);
        }
        return accessToken;
    }

}
